//
//  BHMeCollectionChildViewController.swift
//  BigHealth
//
//  Created by 蔺百好 on 2021/8/24.
//

import UIKit

class BHMeCollectionChildViewController: BHBaseViewController {

    lazy var collectionView: UICollectionView = {
        let layout = UICollectionViewFlowLayout.init()
        layout.sectionInset = .zero
        let view = UICollectionView.buildCollectionView(layout: layout)
        view.backgroundColor = .color_f8f8f8
        view.delegate = self
        view.dataSource = self
        
        return view
    }()
    /**
     1精彩赛事
     2运动场馆
     3医疗机构
     4热门活动
     */
    var childType: Int = 1
    fileprivate var gameArray: [BHCommonGameModel] = []
    fileprivate var stadiumArray: [BHCommonStadiumModel] = [] // 运动场馆和医疗机构
    fileprivate var funArray: [BHFunListInfoModel] = [] // 趣玩
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = .color_f8f8f8
        self.view.addSubview(self.collectionView)
        self.registerCell()
        self.collectionView.mas_makeConstraints { (make) in
            make?.left.right()?.top()?.height()?.equalTo()(self.view)
        }
        
        if self.childType == 1 {
            self.queryCollectionService()
        }
        
        self.collectionView.addloadMore { [weak self] in
            self?.page += 1
            self?.queryCollectionService()
        }
        
        self.collectionView.addRefresh { [weak self] in
            self?.page = 1
            self?.queryCollectionService()
        }
        
    }
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        self.collectionView.frame =   CGRect(x: 0, y: 0, width: UIScreen.width, height: self.view.bh_height)
    }
    
    private func registerCell() {
        self.collectionView.register(UINib.init(nibName: "BHWonderfulGameCell", bundle: nil), forCellWithReuseIdentifier: "BHWonderfulGameCell")
        self.collectionView.register(UINib.init(nibName: "BHSportAndPlaceCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: "BHSportAndPlaceCollectionViewCell")
        self.collectionView.register(UINib.init(nibName: "BHMoreFunCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: "BHMoreFunCollectionViewCell")
    }
    
    
    func begainRefresh() {
        if self.childType == 1 {
            if self.gameArray.count == 0 {
                self.queryCollectionService()
            }
        }
        if self.childType == 2 {
            if self.stadiumArray.count == 0 {
                self.queryCollectionService()
            }
        }
        if self.childType == 3 {
            if self.stadiumArray.count == 0 {
                self.queryCollectionService()
            }
        }
        
        if self.childType == 4 {
            if self.funArray.count == 0 {
                self.queryCollectionService()
            }
        }
    }

}
extension BHMeCollectionChildViewController: UICollectionViewDataSource,UICollectionViewDelegateFlowLayout {
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        if self.childType == 1 {
            return self.gameArray.count
        }
        if self.childType == 2 {
            return self.stadiumArray.count
        }
        if self.childType == 3 {
            return self.stadiumArray.count
        }
        if self.childType == 4 {
            return self.funArray.count
        }
        return 10
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        if self.childType == 1 {
            return CGSize(width: UIScreen.width, height: BHWonderfulGameCell.gameHeight)
        }else if self.childType == 2 {
            let model = self.stadiumArray[indexPath.row]
            return CGSize(width: UIScreen.width, height: model.cellHeight)
        }else if self.childType == 3 {
            let model = self.stadiumArray[indexPath.row]
            return CGSize(width: UIScreen.width, height: model.cellHeight)
        }else if self.childType == 4 {
            return CGSize(width: UIScreen.width, height: BHMoreFunCollectionViewCell.moreFunHeight)
        }else {
            return .zero
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        if self.childType == 1 {
            let model = self.gameArray[indexPath.row]
            BHRouter.shared.bh_goGameDetail(gameId: model.gameId)
        }
        if self.childType == 2 || self.childType == 3{
            let model = self.stadiumArray[indexPath.row]
            BHRouter.shared.bh_goStadiumDetail(stadium: model.stadiumId)
        }
        if self.childType == 4 {
            let model = self.funArray[indexPath.row]
            BHRouter.shared.bh_goFunDetail(funId: model.funId)
        }
    }
}

extension BHMeCollectionChildViewController: UICollectionViewDelegate {
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        if self.childType == 1 {
            return  self.cellForGame(indexPath)
        }else if self.childType == 2 {
            return self.cellForSport(indexPath)
        }else if self.childType == 3 {
            return self.cellForSport(indexPath)
        }else if self.childType == 4 {
            return self.cellForMoreFun(indexPath)
        }else {
            return UICollectionViewCell()
        }
    }
    
}

// MARK: - 精彩赛事
extension BHMeCollectionChildViewController {
    func cellForGame(_ indexPath: IndexPath) -> BHWonderfulGameCell {
        let cell = self.collectionView.dequeueReusableCell(withReuseIdentifier: "BHWonderfulGameCell", for: indexPath) as! BHWonderfulGameCell
        let model = self.gameArray[indexPath.row]
        cell.model = model
        return cell
    }
}


// MARK: - 运动场馆 && 医疗机构
extension BHMeCollectionChildViewController {
    func cellForSport(_ indexPath: IndexPath) -> BHSportAndPlaceCollectionViewCell {
        let cell = self.collectionView.dequeueReusableCell(withReuseIdentifier: "BHSportAndPlaceCollectionViewCell", for: indexPath) as! BHSportAndPlaceCollectionViewCell
        let model = self.stadiumArray[indexPath.row]
        cell.model = model
        return cell
    }
}

// MARK: - 更多趣玩
extension BHMeCollectionChildViewController {
    func cellForMoreFun(_ indexPath: IndexPath) -> BHMoreFunCollectionViewCell {
        let cell = self.collectionView.dequeueReusableCell(withReuseIdentifier: "BHMoreFunCollectionViewCell", for: indexPath) as! BHMoreFunCollectionViewCell
        let model = self.funArray[indexPath.row]
        cell.model = model
        return cell
    }
}

//MARK: 数据处理
extension BHMeCollectionChildViewController {
    func resolveResult(dic: [String:Any]) {
        if self.page == 1 {
            self.collectionView.endLoadWithNoMoreData(false)
            if self.childType == 1 {
                self.gameArray.removeAll()
            }else if self.childType == 4 {
                self.funArray.removeAll()
            }else {
                self.stadiumArray.removeAll()
            }
        }
        
        let result = BHJsonTool.decodeDicFromDic(dic: dic, key: "result")
        let total = BHJsonTool.decodeIntFromDic(dic: result, key: "total")
        let record = BHJsonTool.decodeArrayFromDic(dic: result, key: "records")
        for dic in record {
            if self.childType == 1 {
                let model = BHCommonGameModel.init()
                model.parseDic(dic as! [String : Any])
                self.gameArray.append(model)
            }else if self.childType == 4 {
                let model = BHFunListInfoModel.init()
                model.parseDic(dic as! [String : Any])
                self.funArray.append(model)
            }else {
                let model = BHCommonStadiumModel.init()
                model.parseDic(dic as! [String : Any])
                self.stadiumArray.append(model)
            }
            
        }
        self.collectionView.reloadData()
        if self.childType == 1 &&  self.gameArray.count >= total {
            self.collectionView.endLoadWithNoMoreData(true)
        }
        
        if (self.childType == 2 || self.childType == 3) &&  self.stadiumArray.count >= total {
            self.collectionView.endLoadWithNoMoreData(true)
        }
        
        if self.childType == 4 &&  self.funArray.count >= total {
            self.collectionView.endLoadWithNoMoreData(true)
        }
        
    }
}


// MARK:
extension BHMeCollectionChildViewController {
    func queryCollectionService() {
        let dic = self.appendDic()
        let manager = BHHTTPClient.init()
        manager.get(url: String.me_collection_url, paramters: dic) { (success, errorMsg, responseDic) in
            self.collectionView.endRefresh()
            self.collectionView.endLoading()
            if success == true {
                self.resolveResult(dic: responseDic)
            }else {
                BHToast.toast(text: errorMsg)
                if self.page > 1 {
                    self.page -= 1
                }
            }
        }
    }
    
    func appendDic() -> [String:Any] {
        var dic: [String:Any] = [:]
        if self.childType == 1 {
            dic["type"] = 3
        }else if self.childType == 2 {
            dic["type"] = 2
        }else if self.childType == 3 {
            dic["type"] = 4
        }else {
            dic["type"] = 1
        }
        dic["longitude"] = BHLocationManager.shared.longitude
        dic["latitude"] = BHLocationManager.shared.latitude
        dic["pageNo"] = self.page
        dic["pageSize"] = 15
        return dic
    }
}

